package com.cpz.rabbitmq.service.impl;

import com.cpz.rabbitmq.message.RabbitMessage;
import com.cpz.rabbitmq.service.RabbitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Properties;

/**
 * @author cpz
 * @since 2022/09/19
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RabbitServiceImpl implements RabbitService {

    private final RabbitTemplate rabbitTemplate;
    private final AmqpAdmin amqpAdmin;

    @Override
    public void send(RabbitMessage message) {
        log.info("【生产者】发送消息：ID：{}，交换机：{}，路由键：{}，内容：{}", message.getMessageId(), message.exchange(), message.routingKey(), message.getData());
        rabbitTemplate.convertAndSend(message.exchange(), message.routingKey(), message, new CorrelationData(message.getMessageId()));
    }

    @Override
    public String declareQueue(String queueName) {
        Objects.requireNonNull(queueName);
        Properties queueProperties = amqpAdmin.getQueueProperties(queueName);
        if (null == queueProperties) {
            amqpAdmin.declareQueue(new Queue(queueName, true));
        }
        return queueName;
    }
}
